package com.liuweiheng.springcloud.controller;

import cn.hutool.json.JSONUtil;
import com.liuweiheng.base.entity.R;
import com.liuweiheng.cloudproviderpayment8002.entity.User;
import com.liuweiheng.springcloud.feign.PaymentFeignService;
import com.liuweiheng.springcloud.jwt.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import static com.liuweiheng.base.entity.IR.*;

/**
 * Jwt控制器
 * @author lwh
 * @since 2020/12/7
 */
@RestController
@RequestMapping("/gateway/jwt/")
public class JwtController {

    @Value("${org.my.jwt.effective-time}")
    private String effectiveTime;

    @Autowired
    private PaymentFeignService paymentFeignService;

    /**
     * 登录获取token
     */
    @PostMapping("login")
    public R login(@RequestBody User user) throws Exception {

        R result = paymentFeignService.login(user);

        int effectivTimeInt = Integer.valueOf(effectiveTime.substring(0,effectiveTime.length()-1));
        String effectivTimeUnit = effectiveTime.substring(effectiveTime.length()-1,effectiveTime.length());
        String jwt = "";

        Object o = result.get(DATA);
        String subject = String.valueOf(JSONUtil.parse(o));

        if (result.get(CODE) == SUCCESS_CODE) {
            switch (effectivTimeUnit){
                case "s" :{
                    //秒
                    jwt = JwtUtil.createJWT("test", "test", subject, effectivTimeInt * 1000L);
                    break;
                }
                case "m" :{
                    //分钟
                    jwt = JwtUtil.createJWT("test", "test", subject, effectivTimeInt * 60L * 1000L);
                    break;
                }
                case "h" :{
                    //小时
                    jwt = JwtUtil.createJWT("test", "test", subject, effectivTimeInt * 60L * 60L * 1000L);
                    break;
                }
                case "d" :{
                    //小时
                    jwt = JwtUtil.createJWT("test", "test", subject, effectivTimeInt * 24L * 60L * 60L * 1000L);
                    break;
                }
            }
            return R.ok("auth success").putData(jwt);
        } else {
            return R.error("auth fail");
        }

    }

}
